
import { defineStore } from 'pinia'
import router, { defaultNavList, defaultNavItem, layoutRoute } from '@/router'
import { mockPermission } from '@/mock/permission'
import { findFirstByCondition, arrToTree } from '@/utils/tools'
import NotFound from '@/views/notFound/index.vue'
import { moduleComponentMap } from '#/index'
import InternalModuleLayout from '@/layout/internalModule/InternalModuleLayout.vue'
import InternalIframe from '@/views/internalIframe/index.vue'

import { TOKEN_KEY } from '@/constants'


export const useSystemStore = defineStore('system', {
    state: () => {
        return {
            loginFlag: false,
            userInfo: {},
             // 导航列表
            navList: [],
            navMap: {},
            // 当前选中导航
            currentNav: {},
            dateKey: +new Date()
        }
    },
    actions: {
       setUserInfo(userInfo) {
         this.userInfo = userInfo
         localStorage.setItem('userInfo',JSON.stringify(userInfo))
         localStorage.setItem(TOKEN_KEY, userInfo.kid)
       },
       /** @type {() => { num: number }} */
       getUserInfo() {
        return this.userInfo
       },
       logout() {
            this.$reset()
            router.replace({ path: `/login` })
            localStorage.removeItem(TOKEN_KEY)
            this.removeRoute(layoutRoute)
            this.loginFlag = false

            let cdd = this.getUserInfo()
            
       },
        // 权限
        async initPermission () {
            let res = mockPermission
            const navList = res.map(nav => {
                const { subSystemType, menuTree = [], ...navArgs } = nav
                const navInfo = {
                    ...navArgs,
                    subSystemType
                }
                switch (subSystemType) {
                    case 0:
                        const _permList = []
                        const _menuList = []
                        menuTree.forEach(item => {
                            // 权限
                            if (item.menuType === 2) {
                                _permList.push(item)
                            } else {
                                modifyInternalModuleMenuItem(nav, item)
                                _menuList.push(item)
                            }
                        })
                        const _purePermList = _permList.map(item => item.permsFlag)
                        const _menuTreeList = arrToTree(_menuList)
                        Object.assign(navInfo, {
                            _permList,
                            _purePermList,
                            _menuList,
                            _menuTreeList
                        })
                        break
                    default:
                        break
                }
                return navInfo
            })

            this.navList = defaultNavList.map(item => {
                return {
                    ...item,
                    meta: {
                        _navKid: item.kid
                    }
                }
            }).concat(navList)

            this.navMap = this.navList.reduce((prev, current) => {
                prev[current.kid] = current
                return prev
            }, {})

            this.initRoute()


            this.loginFlag = true


        },

        async initRoute () {
            this.removeRoute(layoutRoute.name)
            router.addRoute({ ...layoutRoute })

            this.navList.forEach(navInfo => {
                let navRoute
                switch (navInfo.subSystemType) {
                    case defaultNavItem:
                        navRoute = {
                            ...navInfo,
                            path: navInfo.url
                        }
                        this.addRouteToLayout(navRoute)
                        return
                    case 0:
                        navRoute = buildInternalModuleRoute(navInfo)
                        this.addRouteToLayout(navRoute)
                        return
                    case 1:
                        navRoute = buildInternalIframeRoute(navInfo)
                        this.addRouteToLayout(navRoute)
                        return
                    default:
                        break
                }
            })
        },
        removeRoute (route) {
            router.hasRoute(route.name) && router.removeRoute(route.name)
        },
        addRouteToLayout (route) {
            router.addRoute(layoutRoute.name, route)
        }
    }
})


function modifyInternalModuleMenuItem (nav, menu) {
    // 菜单
    if (menu.menuType === 1) {
        const _moduleComponentName = menu.componentName
        const [_moduleName, _componentName] = _moduleComponentName.split('##')

        const _path = `${nav.url}${menu.routerPath}`

        Object.assign(menu, {
            _navKid: nav.kid,
            _moduleComponentName,
            _moduleName,
            _componentName,
            _path
        })
    }
}


function buildInternalModuleRoute (nav) {
    const navRoute = {
        path: nav.url,
        component: InternalModuleLayout,
        name: nav.kid,
        meta: {
            ...nav
        }
    }

    const addRouteList = nav._menuList.map(item => {
        const componentInfo = moduleComponentMap[item._moduleComponentName]

        const menuRoute = {
            path: item._path,
            name: item.kid,
            meta: { ...item },
            component: NotFound
        }

        if (componentInfo) {
            menuRoute.component = componentInfo.component
        }

        // 菜单
        if (menuRoute.meta.menuType === 1) {
            return menuRoute
        }

        // 目录
        return null
    }).filter(Boolean)

    const firstValidMenu = findFirstByCondition(navRoute.meta._menuTreeList, it => {
        return it.menuType === 1
    })

    Object.assign(navRoute, {
        redirect: firstValidMenu && firstValidMenu._path,
        children: addRouteList
    })

    return navRoute
}

function buildInternalIframeRoute (nav) {
    const navRoute = {
        path: `/${nav.kid}`,
        component: InternalIframe,
        name: nav.kid,
        meta: {
            ...nav,
            _navKid: nav.kid
        }
    }

    return navRoute
}

